package no.group.gowther.util;

import cn.hutool.core.img.ImgUtil;
import no.group.gowther.exception.CannotResolveSuchImageTypeException;


import java.awt.*;
import java.io.IOException;

import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Path;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.FileImageInputStream;

/**
 * @author ayatsuji
 * @date 2022-04-17 21:41
 * @since
 */
public class ImageUtils {
    public static Dimension getImageDimension(Path path) throws IOException, CannotResolveSuchImageTypeException {
        final java.awt.Dimension imageDim = getImageDim(path);
        return new Dimension(imageDim.width, imageDim.height);
    }

    private static java.awt.Dimension getImageDim(Path path) throws IOException, CannotResolveSuchImageTypeException {
        try (FileImageInputStream fileImageInputStream = new FileImageInputStream(path.toFile())) {
            final Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(fileImageInputStream);
            if (imageReaders.hasNext()) {
                ImageReader reader = imageReaders.next();
                reader.setInput(fileImageInputStream);
                try {
                    int width = reader.getWidth(reader.getMinIndex());
                    int height = reader.getHeight(reader.getMinIndex());
                    return new java.awt.Dimension(width, height);
                } finally {
                    reader.dispose();
                }
            }
        }
        throw new CannotResolveSuchImageTypeException(String.format("无法解析图片[%s]", path));
    }

    public static record Dimension(int width, int height) {
        public static final Dimension ZERO = new Dimension(0, 0);
    }

    public static void generateThumbnail(InputStream image, int width, int height, OutputStream thumbnail) {
        ImgUtil.scale(image, thumbnail, width, height, Color.WHITE);
    }
}




